package pl.edu.pw.ee.buildcity.gg.commands;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import pl.edu.pw.ee.buildcity.commons.exceptions.BuildCityRuntimeException;
import pl.edu.pw.ee.buildcity.domain.FireJobEvent;

import java.util.List;

/**
 * @author Mateusz
 * @since 2010-02-13
 */
public class BuildCommand implements Command, ApplicationEventPublisherAware {

	//Standard Spring application event publishing mechanism
	private ApplicationEventPublisher eventPublisher;

	@Override
	public String execute(List<String> parameters) {

		if (CollectionUtils.isEmpty(parameters)) {
			throw new BuildCityRuntimeException("At least one job name is obligatory!");
		}
		StringBuilder sb = fireJobs(parameters);
		return sb.toString();
	}

	private StringBuilder fireJobs(List<String> parameters) {
		StringBuilder sb = new StringBuilder("Jobs fired: ");
		for (String jobName : parameters) {
			fireBuild(jobName);
			sb.append(jobName + " ");
		}
		return sb;
	}

	private void fireBuild(String jobName) {
		FireJobEvent fireJobEvent = new FireJobEvent(jobName);
		eventPublisher.publishEvent(fireJobEvent);
	}

	@Override
	public String toString() {
		return "BuildCommand";
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		eventPublisher = applicationEventPublisher;
	}
}
